from tkinter import *
# 导入ttk
from tkinter import ttk
# 导入filedialog
from tkinter import filedialog
from tkinter.messagebox import *
from tkinter import *
import requests
import re
import pyttsx3
import _thread
import json

class App:

    def __init__(self, root):
        self.root = root
        self.read = 1
        #self.book_index = 2
        self.book_names = []
        #self.is_open_type = False  # False表示当前未开启，True表示当前开启
        self.read_file()
        self.initWidgets()

    def read_file(self):
        with open("book.json", "r", encoding='utf-8') as f:
            self.book = json.load(f)
            self.book_index=self.book["default"]
            self.book["books"]
            for x in self.book["books"]:
                self.book_names.append(x["name"])
            # print(self.book_names)

    def write_file(self):
        with open("book.json", "w", encoding='utf-8') as f:
            json.dump(self.book, f, indent=2, sort_keys=True, ensure_ascii=False)  # 写为多行

    def initWidgets(self):
        # print(self.book)
        # print(self.book["books"][1]["book"])

        # 创建下拉列表，设置下拉列表中的值
        self.normal_ddl = Label(self.root, text='')
        self.ddl = ttk.Combobox(self.root)
        self.ddl['value'] = self.book_names
        self.ddl.bind("<<ComboboxSelected>>", self.xFunc)  # #给下拉菜单绑定事件

        self.get_label1 = Label(self.root, text='book')
        self.get_text1 = Text(self.root, height=1, width=10)
        self.get_text1.insert('0.0', self.book["books"][self.book_index]["book"])

        self.get_label2 = Label(self.root, text='page')
        self.get_text2 = Text(self.root, height=1, width=10)
        self.get_text2.insert('0.0', self.book["books"][self.book_index]["page"])

        self.button_get = Button(self.root, text='start', command=self.text_get)
        self.button_get2 = Button(self.root, text='end', command=self.text_get2)

        # self.normal_ddl.grid(row=0, column=1, sticky='E')
        # self.ddl.grid(row=0, column=1, sticky=W)

        self.get_label1.grid(row=1, column=0, sticky=E)
        self.get_text1.grid(row=1, column=1, sticky=W)
        self.get_label2.grid(row=2, column=0, sticky=E)
        self.get_text2.grid(row=2, column=1, sticky=W)

        self.button_get.grid(row=3, column=0, sticky=W)
        self.button_get2.grid(row=3, column=1, sticky=W)

    def text_get(self):
        self.read = 1
        print("===========start read============")
        _thread.start_new_thread(self.get_msg, ())

    def text_get2(self):
        self.read = 0
        print("===========stop read============")

    def get_msg(self):
        while self.read:
            book = str(self.get_text1.get('0.0', END)).replace("\n", "")
            page = str(self.get_text2.get('0.0', END)).replace("\n", "")
            full_url = self.book["base_url"] + book + "/" + page
            print(full_url)
            bbb = 10
            print_if = 0
            html = requests.get(full_url)
            html.encoding = 'utf-8'

            xxxxx = html.text.replace("<br><br>", "\n")
            xxxxx = xxxxx.replace("<br /><br />", "\n")
            xxxxx = xxxxx.replace("<br/><br/>", "\n")
            xxxxx = xxxxx.replace("</p><p>", "\n")
            xxxxx = xxxxx.replace("<p>", "\n")
            xxxxx = xxxxx.replace("<br />　　<br />", "\n")
            xxxxx = xxxxx.replace("<br />", "")
            xxxxx = xxxxx.replace("“", "")
            xxxxx = xxxxx.replace("”", "")
            xxxxx = xxxxx.replace("&nbsp;&nbsp;&nbsp;&nbsp;", "\t")

            start = xxxxx.find("nr_nr")
            end = xxxxx.find("pb_next")
            zzzz = xxxxx[start + 25:end - 646]
            zzzz = zzzz.replace("<", "")
            zzzz = zzzz.replace("", "")
            if print_if:
                print(zzzz)
            xdf = 0
            try:
                xdf = html.text.index(">下一页")
            except:
                try:
                    xdf = html.text.index(">下一章")
                except:
                    print("next")
            print(html.text[xdf - 50:xdf])
            next_papge = html.text[xdf - 50:xdf].replace("\"", "").split("/read/" + book + "/")[1]
            print(next_papge)
            self.get_text2.delete('0.0', END)
            self.get_text2.insert('0.0', next_papge)
            self.book["books"][self.book_index]["page"] = next_papge
            self.write_file()
            if bbb:
                self.say(zzzz)

    def say(self, str):
        engine = pyttsx3.init()
        engine.setProperty('rate', 400)
        engine.say(str)
        engine.runAndWait()

    def xFunc(self, value):
        print("----")
        print(self.ddl.get())


root = Tk()
root.title('-')
root.geometry("100x80")
App(root)

root.mainloop()
